<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-11-08
 * Time: 11:30:51
 * Info:
 */

namespace app\common\model;

use app\common\model\ModelsField as ModelsFieldModel;
use app\common\model\Category as CategoryModel;
use think\facade\Db;
use think\facade\Validate;

class Content extends TimeInit
{

    protected $deleteTime = 'delete_time';

    /**
     * 指定自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = 'int';

    /**
     * 格式化发布日期
     *
     * @param $value
     * @param $data
     *
     * @return false|string
     */
    public function getPublishTimeTextAttr($value, $data)
    {
        return empty($data['publish_time']) ? '-' : date('Y-m-d H:i:s', $data['publish_time']);
    }

    /**
     * 格式化
     *
     * @param $value
     * @param $data
     *
     * @return false|string
     */
    public function getDeleteTimeTextAttr($value, $data)
    {
        return empty($data['delete_time']) ? '-' : date('Y-m-d H:i:s', $data['delete_time']);
    }

    /**
     * 格式化url
     *
     * @param $value
     * @param $data
     *
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        $url = "/index/show/id/".$data['id'];

        return $url;
    }

    /**
     * 获取完整url地址
     *
     * @param $value
     * @param $data
     *
     * @return int|mixed|string|string[]
     */
    public function getFullurlAttr($value, $data)
    {
        $url = "/index/show/id/".$data['id'];

        return $url;
    }

    /**
     * ToDo:这里没做
     * 生成url地址
     *
     * @param      $value
     * @param      $data
     * @param bool $domain
     */
    protected function buildUrl($value, $data, $domain = false)
    {
        if (empty($value)) {
            if ( ! empty($data['jump_url'])) {
                return $data['jumplink'];
            }
            $cateInfo = Category::where(['id' => $data['cate_id']])->cache(60)->find();
            if ( ! $cateInfo) {
                return '';
            }
            $cateInfo = $cateInfo->toArray();
            $site     = get_config(); // 获取伪静态规则
            if ($data['status'] != 1) {
                // 去到预览页
                $param = ['category_id' => $data['cate_id'], 'id' => $data['id']];

                return (string)url('/cms.archives/preview', $param);
            }
            if ($site['url_mode'] == 1 && ! empty($site['url_rewrite'])) {
                // todo:这里没做
                $cateInfo['aid']     = $data['id'];
                $cateInfo['diyname'] = ! empty($data['diyname']) ? $data['diyname'] : '';
                $param               = $cateInfo;
            } else {
                $param = ['id' => $data['id'], 'catname' => $cateInfo['name']];
            }

            return "";
            //return index_url($cateInfo['type'] == 'link' ? '/index/lists' : '/index/show', $param, '', $domain);
        } else {
            if ($domain) {
                if ( ! \think\facade\Validate::regex($value, '/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?\//i')) {
                    $value = app('request')->domain().$value;
                }
            }
        }

        return $value;
    }

    public function flag()
    {
        return $this->hasMany('app\common\model\ContentFlag', 'aid', 'id');
    }

    public function contentExt()
    {
        return $this->hasOne('app\common\model\ContentExt', 'content_id', 'id');
    }

    public function category()
    {
        return $this->hasOne('app\common\model\Category', 'id', 'cate_id');
    }

    public function models()
    {
        return $this->belongsTo(\app\common\model\Models::class, 'model_id', 'id');
    }

    /**
     * 获取列表，用于内容标签
     *
     * @param $tag
     * @param $catData
     * @param $modelData
     * @param $page \think\Paginator|mixed paginate 分页对象
     *
     * @return array|mixed|object|\think\App
     */
    public function tagContent($tag, $catData, $modelData, &$page)
    {
        $tag['order'] = ! empty($tag['order']) ? $tag['order'] : 'sort asc,id desc';
        $tag['flag']  = ! empty($tag['flag']) ? $tag['flag'] : '';

        // 默认条件
        $map = [['status', '=', 1]];

        // 检查条件字段是否加了id
        if (empty($tag['aid']) && empty($tag['aids'])) {
            if (is_string($tag['where'])) {
                $sortArr = explode(' ', $tag['where']);
                foreach ($sortArr as $key => $item) {
                    $sortArr[$key] = stripos($item, "id") === 0 ? 'a.'.$item : $item;
                }
                $tag['where'] = implode(' ', $sortArr);
            } else {
                if (is_array($tag['where'])) {
                    foreach ($tag['where'] as $key => $value) {
                        if ($key == 'id') {
                            $tag['where']['a.id'] = $value;
                            unset($tag['where']['id']);
                            break;
                        }
                    }
                }
            }
        }
        $obj = $this->alias('a')->with(['category', 'models', 'content_ext'])->where($tag['where']);

        // 文档属性
        if ( ! empty($tag['flag'])) {

        }

        $array = [];
        if ($tag['aid']) { // 指定单条文档

        } elseif ($tag['aids']) { // 指定多条文档

        } else {
            // 查出模型数据
            $tag['model_id'] = empty($tag['model_id']) ? $modelData['id'] ?? '' : $tag['model_id'];
            $tag['catid']    = empty($tag['catid']) ? $catData['id'] ?? '' : $tag['catid'];
            $map[]           = ['model_id', '=', $modelData['id']];

            // 获取请求的排序、数据筛选
            $sort  = app()->request->get('sort');
            $order = app()->request->get('order');
            if ($sort != '_default' && Validate::is($sort, 'alphaDash')) {
                // 获取扩展字段
                if (app()->isDebug()) {
                    $mf = ModelsFieldModel::where(['name' => $sort])->find();
                } else {
                    $mf = ModelsFieldModel::where(['name' => $sort])->cache('field_name_model_field', 7200,
                        'model_field')->find();
                }
                if ( ! empty($mf)) {
                    $tag['order'] = [($mf->iscore == 1 ? '' : 'e.').$sort => $order == 'desc' ? $order : 'asc'];
                }
            }

            $param = app()->request->get();
            if (isset($tag['filter']) && $tag['filter'] == 1) {
                // 启用筛选
                $filter = array_diff_key($param, array_flip(['sort', 'order', 'lang']));
                // 获取扩展字段
                if (app()->isDebug()) {
                    $filterField = ModelsFieldModel::where(['model_id' => $tag['model_id']])->select()->toArray();
                } else {
                    $filterField = ModelsFieldModel::where(['model_id' => $tag['model_id']])->cache('is_filter_model_field',
                        3660, 'model_field')->select()->toArray();
                }
                foreach ($filterField as $value) {
                    if (isset($filter[$value['name']]) && $filter[$value['name']] != '') {
                        $tempArr = explode(',', $filter[$value['name']]);
                        // 匹配是否是筛选的值
                        if ( ! empty($value['setting'])) {
                            // todo:这里没有完善，没有做处理，目前不受影响。
                            /*$setting = json_decode($value['value'], true);
                            if ( ! empty($setting['filter_option'])) {
                                $option = json_decode($setting['filter_option'], true);
                            } else {
                                if ( ! empty($value['data_list'])) {
                                    $option = $value['data_list'];
                                }
                            }*/
                        } else {
                            if ( ! empty($value['value'])) {
                                $option    = json_decode($value['value'], true);
                                $newOption = [];
                                foreach ($option as $k => $v) {
                                    $newOption[$v['value']] = $v['name'];
                                }
                                $option = $newOption;
                            }
                        }
                        if ( ! empty($option)) {
                            $option = array_flip($option);
                            foreach ($tempArr as $k => $v) {
                                if ( ! in_array($v, $option)) {
                                    unset($tempArr[$k]);
                                }
                            }
                            if (count($tempArr) > 1) {
                                if (in_array($value['type'], [3, 4])) {
                                    $obj = $obj->where(function ($query) use ($value, $tempArr) {
                                        foreach ($tempArr as $whereValue) {
                                            $query->whereFindInSet(($value['iscore'] != 1 ? 'e.' : '').$value['name'],
                                                $whereValue, 'or');
                                        }
                                    });
                                } else {
                                    $map[] = [
                                        ($value['iscore'] != 1 ? 'e.' : '').$value['field_name'],
                                        'in',
                                        implode(',', $tempArr)
                                    ];
                                }
                                $param = array_merge($param, [$value['name'] => implode(',', $tempArr)]);
                            } else {
                                if (count($tempArr) == 1) {
                                    if (in_array($value['type'], [3, 4])) {
                                        $obj = $obj->whereFindInSet(($value['iscore'] != 1 ? 'e.' : '').$value['name'],
                                            $tempArr[0]);
                                    } else {
                                        $map[] = [
                                            ($value['iscore'] != 1 ? 'e.' : '').$value['name'],
                                            '=',
                                            $tempArr[0]
                                        ];
                                    }
                                    $param = array_merge($param, [$value['name'] => $tempArr[0]]);
                                }
                            }
                        }
                    }
                }
            }

            // 获取栏目ID，包含下级。
            if ( ! empty($tag['catid']) && is_numeric($tag['catid']) && $tag['insub'] == 1) {
                $tag['catid'] = intval($tag['catid']);
                $catIdArr     = get_category_sub($tag['catid'], false, ['status' => 1, 'model_id' => $tag['model_id']]);
                if ( ! empty($catIdArr)) {
                    $catIdArr[] = $tag['catid'];
                    $obj        = $obj->where(function ($query) use ($tag, $catIdArr) {
                        $query->where('cate_id', 'in', $catIdArr);
                    });
                } else {
                    $obj = $obj->where('(cate_id = '.$tag['catid'].' or find_in_set("'.$tag['catid'].'",category_ids))');
                }
            } else {
                if ( ! empty($tag['catid']) && is_numeric($tag['catid']) && $tag['insub'] == 0) {
                    // 栏目与副栏目
                    $obj = $obj->where('(cate_id = '.$tag['catid'].' or find_in_set("'.$tag['catid'].'",category_ids))');
                } else {
                    if ( ! empty($tag['catid'])) { // 同时获取多个栏目的数据
                        $obj = $obj->where(function ($query) use ($tag) {
                            $query->where('cate_id', 'in', $tag['catid']);
                            $catIdArr = explode(',', (string)$tag['catid']);
                            foreach ($catIdArr as $key => $value) {
                                $query->whereOr('find_in_set("'.$value.'",category_ids)');
                            }
                        });
                    }
                }
            }

            // 获取扩展字段
            if (app()->isDebug()) {
                $fields = \think\facade\Db::name('models_field')->where([
                    'status'   => 1,
                    'model_id' => $modelData->id
                ])->select()->toArray();
            } else {
                $fields = \think\facade\Db::name('models_field')->where([
                    'status'   => 1,
                    'model_id' => $modelData->id
                ])->cache('normal_model_field'.$modelData->id, 3600, 'model_field')->select()->toArray();
            }

            $extField    = [];
            $fieldNew    = [];
            $diyFieldArr = $tag['field'] == '*' ? [] : explode(',', $tag['field']);
            foreach ($fields as $key => $value) {
                if ($tag['field'] != '*' && ! in_array($value['name'], $diyFieldArr)) {
                    continue;
                }
                $fieldNew[$key] = $value;
            }
            $extField = implode(',', $extField);
            $fields   = $fieldNew;

            // 查看是否指定字段
            $field = $tag['field'] == '*' ? 'a.*'.$extField : $tag['field'];

            if ($tag['page'] && empty($tag['tagid'])) { // 开启分页
                $obj = $obj->leftJoin('content_ext e', 'e.content_id=a.id')->where($map)->field($field)->append([
                    'publish_time_text',
                    'fullurl'
                ]);
                if ( ! empty($tag['order']) && is_numeric($tag['order'])) {
                    $obj = $obj->orderRaw("rand()");
                } else {
                    $obj = $obj->order($tag['order']);
                }

                $obj   = $obj->paginate([
                    'list_rows' => intval($tag['num']),
                    'var_page'  => 'page',
                    'query'     => $param,
                    'path'      => '/index/lists'
                ]);
                $array = $obj->toArray()['data'];
                $page  = $obj;
            } elseif ($tag['page'] && ! empty($tag['tagid'])) { // 瀑布流分页

            } else { // 不分页
                // 限制结果
                $offset = 0;
                $length = null;
                if ( ! empty($tag['num']) && is_numeric($tag['num']) && $tag['num'] > 0) { // 指定分页
                    $offset = intval($tag['num']);
                } else {
                    if ( ! empty($tag['num']) && strpos($tag['num'], ',') !== false) {
                        $temp = explode(',', $tag['num']);
                        if (count($temp) == 2 && is_numeric($temp[0]) && is_numeric($temp[1])) {
                            $offset = (int)$temp[0] - 1;
                            $length = (int)$temp[1];
                        }
                    }
                }
                if ( ! empty($tag['order']) && is_numeric($tag['order'])) {
                    $array = $obj->where($map)->orderRaw("rand()")->limit($offset, $length)->field($field)->append([
                        'publish_time_text',
                        'fullurl'
                    ])->select()->toArray();
                } else {
                    $array = $obj->where($map)->order($tag['order'])->limit($offset, $length)->field($field)->append([
                        'publish_time_text',
                        'fullurl'
                    ])->select()->toArray();
                }
            }
        }

        return $array;

    }

}
